package com.login_1.servlet;

import com.login_1.dao.UserDao;
import com.login_1.dao.impl.UserDaoImpl;
import com.login_1.pojo.User;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

@WebServlet("/ServletLogin1")
public class ServletLogin1 extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("执行了ServletLogin1....");

        // 设置字符编码
        request.setCharacterEncoding("utf-8");

        // 获取请求参数
        Map<String, String[]> map = request.getParameterMap();

        // 创建user对象
        User user = new User();

        // 将map中的数据封装到user对象中
        try {
            BeanUtils.populate(user, map);
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 调用dao
        UserDao userDao = new UserDaoImpl();
        User u = userDao.findByUser(user);

        //判断u是否为null
        if (u == null) {
            //数据库中没有跳转到login.html
            request.getRequestDispatcher("/html/login_1.html").forward(request, response);
        } else {
            //数据库中有，跳转到index.html
            request.getRequestDispatcher("/html/index.html").forward(request, response);
        }

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}
